import axios from "axios";
import qs from 'qs';

import {
  getToken,
  getrefreshToken,
  setToken,
  setrefreshToken
} from '@/util/token'
import store from "@/store/index";


// baseURL设置 设置多个用于分辨测试地址与开发地址
// const BaseURL = "http://127.0.0.1:4523/mock/639148/api";
const BaseURL = "http://127.0.0.1:8080/api";
//设置超时
const Timeout = 7000;
const token = getToken()
// 若cookies中token不存在且refreshToken存在，则发请求带refreshToken请求新的token
if (getToken() === undefined && getrefreshToken() !== undefined) {
  getNewToken(getrefreshToken()).then((res) => {
    if (res.data.code == 200) {
      setToken(res.token)
      setrefreshToken(res.refreshToken)
    }
  }).catch((err) => {
    console.log(err)
  })
  //  若refreshToken不存在则重定向到登录页面
} else if (getrefreshToken() == undefined) {

}
const request = axios.create({
  baseURL: BaseURL,
  timeout: Timeout,
  headers: {
    Token: token,
  }
});
// 请求拦截器
axios.interceptors.request.use(
  config => {
    if (store.state.token.length > 0) {
      config.headers.Authorization = token
    }
    console.log(config);
    return config
  },
  error => {
    console.log(123);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  response => {
    // 401,token无效
    //402，refreshToken无效
    //若响应码为401，则token无效，发请求带refreshToken请求新的token
    if (response.code == 401) {
      getNewToken(getrefreshToken()).then((res) => {
        if (res.data.code == 200) {
          setToken(res.token)
          setrefreshToken(res.refreshToken)
        }
      }).catch((err) => {
        console.log(err)
      })
      //若响应码为402，则refreshToken也无效，那就只能重定向到登录页
    } else if (response.code == 402) {

    }
  },
  error => {

  }
);

function getNewToken(freshToken) {
  return axios.get('http://127.0.0.1:4523/mock/639148/api/user/get_token', {
    params: {
      freshToken
    }
  })
}
export function post(url, data) {
  return new Promise((resolve, reject) => {
    request({
      method: 'POST',
      url: url,
      data:data
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}

export function get(url, params) {
  return new Promise((resolve, reject) => {
    request({
      method: 'GET',
      url: url,
      params: params
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}

export default request
